var Observer = (function(){
	var _messages = {};
	return {
		regist : function(type, fn){
			if (typeof _messages[type] === 'undefined'){
				_messages[type] = [fn];
			}else{
				_messages[type].push(fn);
			}
		},
		fire : function(type, args){
			if(!_messages[type])
				return;
			var events = {
				type : type,
				args : args || {}
			},
			i = 0,
			len = _messages[type].length;
			for(; i<len; i++){
				_messages[type][i].call(this, events);
			}
		},
		remove : function(type, fn){
			if(_messages[type] instanceof Array){
				var i = _messages[type].length-1;
				for(; i>=0; i--){
					_messages[type][i] === fn && _messages[type].splice(i,1);
				}
			}
		}
	}
})();

Observer.regist('test', function(e){
	console.log(e.type, e.args.msg);
});
Observer.fire('test', {msg: '传递参数'});



function $(id){
	return document.getElementById(id);
}
(function(){
	function addMsgItem(e){
		var text = e.args.text,
		ul = $('msg'),
		li = document.createElement('span');
		li.innerHTML = text;
		span.onclick = function(){
			ul.removeChild(li);
			Observer.fire('removeCommentMessage', {
				num : -1
			});
		}
		li.appendChild(span);
		ul.appendChild(li);
	}
	Observer.regist('assComentMessage', addMsgItem);
})();

(function(){
	function changeMsgNum(e){
		var num = e.args.num;
		$('msg_num').innerHTML = parseInt($('msg_num').innerHTML) + num;
	}
	//问题未解决
	Observer
	.regist('addCommentMessage', changeMsgNum)
	.regist('removeCommentMessage', changeMsgNum);
})();

(function(){
	$('user_submit').onclick = function(){
		var text = $('user_input');
		if(text.value === ''){
			return;
		}
		Observer.fire('addCommentMessage', {
			text : text.value,
			num : 1
		});
		text.value = '';
	}
})();


//对象间解耦
//
var Student = function(result){
	var that = this;
	that.result = result;
	that.say = function(){
		console.log(that.resule);
	}
};
Student.prototype.answer = function(question){
	Observer.regist(question, this.say);
}

Student.prototype.sleep = function(question){
	console.log(this.result + ' ' + question + ' 已被注销')
	Observe.remove(question, this.say)
}
var Teacher = function(){};
Teacher.prototype.ask = function(question){
	console.log('问题是：' + question);
	Observe.fire(question)
}
var student1 = new Student('学生1回答问题'),
		student1 = new Student('学生2回答问题'),
		student1 = new Student('学生3回答问题');

student1.answer('什么是设计模式');
student1.answer('简述观察者模式');
student2.answer('什么是设计模式');
student3.answer('什么是设计模式');
student3.answer('简述观察者模式');

var teacher = new Teacher();

teacher.ask('什么是设计模式');
teacher.ask('简述观察者模式');


